﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace WJ.Infrastructure.Json
{
    /// <summary>
    /// 使用Newtonsoft.json转换对象到json
    /// </summary>
    public class JsonNetResult : JsonResult
    {
        public JsonNetResult(object data)
        {
            this.Data = data;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "application/json";
            using (StringWriter sw = new StringWriter())
            {
                JsonSerializer serializer = JsonSerializer.Create(
                    new JsonSerializerSettings
                    {
                        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,

                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }
                    );
                serializer.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                using (JsonWriter jsonWriter = new JsonTextWriter(sw))
                {
                    serializer.Serialize(jsonWriter, Data);
                    response.Write(sw.ToString());
                }
            }
        }
    }
}
